<?php
/*
 * Author  : top-songshijie
 * Email   : 997031758@qq.com
 * DateTime: 2023/02/22 14:36
 */

namespace SSJ\LaravelHelper\Services\Upload\Strategy;

use Illuminate\Support\Facades\Storage;
use SSJ\LaravelHelper\Models\Attachment;
use SSJ\LaravelHelper\Services\Upload\Strategy;

class LocalStrategy extends Strategy
{
    public function handle()
    {
        $attachment = Attachment::check($this->data['md5'], $this->data['sha1']);
        if (lh_isset_not_empty($attachment, 'local_preview_path')) {
            return $attachment;
        }

        $this->data['local_preview_path'] = config('app.url') . '/storage/' . $this->data['path'];

        $this->upload($this->file, $this->uploadPath, $this->fileName);

        if ($attachment) {
            $attachment->update(['local_preview_path' => $this->data['local_preview_path']]);
        } else {
            $attachment = Attachment::query()->create($this->data);
        }

        return $attachment;
    }

    /**
     * 上传到本地
     *
     * @param $file
     * @param $upload_path
     * @param $filename
     */
    protected function upload($file, $upload_path, $filename)
    {
        Storage::disk('public')->putFileAs($upload_path, $file, $filename);
    }
}
